﻿#region

using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using MediaSage.Lib.Configuration;
using MediaSage.Lib.Database;
using MediaSage.Lib.Utilities;
using TvdbLib;
using TvdbLib.Cache;
using TvdbLib.Data;
using TvdbLib.Data.Banner;

#endregion

namespace MediaSage.Lib.Plugin.TVDBProvider
{
    public class TVDBProvider : PluginBase
    {
        #region Constructors

        private readonly string cacheDirectory;
        private readonly ICacheProvider cacheProvider;
        private readonly TvdbHandler tvdbHandler = null;
        private readonly TvdbLanguage language = null;
        private const string baseImageURL = "http://www.thetvdb.com/banners";

        public TVDBProvider(Config configuration, PluginEntity PE)
            : base(configuration, PE)
        {
            logger.Log("Initializing TVDBProvider");
            bool legalCache = true;
            try
            {
                cacheDirectory = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName());
                Directory.CreateDirectory(cacheDirectory);
            }
            catch (Exception e)
            {
                legalCache = false;
                logger.Log("Exception creating cache directory, msg=" + e.Message);
            }

            if (legalCache)
            {
                cacheProvider = new XmlCacheProvider(cacheDirectory);
            }
            tvdbHandler = new TvdbHandler(cacheProvider, "A4ADC1F25D1A6E64");
            tvdbHandler.InitCache();

            // Get the Config Item for this plugin defining the default language
            var cih = new ConfigItemsHelper(config);
            PluginConfigurationItemEntity pluginCie = cih.GetCIByNameForPlugin(pluginEntity.ID, "Language");
            string configLang = null;
            if (pluginCie != null)
            {
                configLang = pluginCie.Value;
            }

            // If it is defined, set the language to English (If it is either en or english, case invariant)
            // else define it as English
            if (!String.IsNullOrWhiteSpace(configLang))
            {
                List<TvdbLanguage> languages = tvdbHandler.Languages;
                foreach (TvdbLanguage lang in languages)
                {
                    if (lang.Abbriviation.ToUpper().Equals(configLang) || lang.Name.ToUpper().Equals(configLang))
                    {
                        language = lang;
                        logger.Log(String.Format("TVDB Provider language set to: {0}-{1}", language.Abbriviation,
                                                 language.Name));
                    }
                }
            }
            else
            {
                List<TvdbLanguage> languages = tvdbHandler.Languages;
                foreach (TvdbLanguage lang in languages)
                {
                    if (lang.Abbriviation.ToUpper().Equals("EN"))
                    {
                        language = lang;
                        logger.Log(String.Format("TVDB Provider language set to (DEFAULT): {0}-{1}",
                                                 language.Abbriviation, language.Name));
                    }
                }
            }

            logger.Log("TVDBProvider Initialized");
        }

        #endregion Constructors

        ~TVDBProvider()
        {
            logger.Log("Cleaning up cache directory for TVDBProvider");
            if (cacheDirectory != null)
            {
                logger.Log("Cleaning up cache directory for TVDBProvider");
                Directory.Delete(cacheDirectory, true);
            }
        }

        #region Methods

        /// <summary>
        /// TVDB Doesnt allow for this
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        public override IList<PersonEntity> SearchPersonByName(string name)
        {
            throw new NotImplementedException();
        }

        public override bool Run(MediaClass mediaObject)
        {
            throw new NotImplementedException();
        }

        public override string[] About()
        {
            VersionInfo verInfo = GetVersionInfo();

            string[] returnValue =
                {
                    "TVDBProvider v" + verInfo.MajorVersion + "." + verInfo.MinorVersion + "." +
                    verInfo.BuildNumber
                };
            return returnValue;
        }

        public override IList<MediaFileTypesEntity> ExtensionsHandled()
        {
            return pluginEntity.ExtensionsHandled;
        }

        public override PluginEntity GetConfiguration()
        {
            logger.Log("Entering TVDBProvider.GetConfiguration()");
            logger.Log("Exiting TVDBProvider.GetConfiguration()");
            return base.pluginEntity;
        }

        public override MediaClass GetMedia(MediaClass inputMedia, MediaMergeType mergeType)
        {
            logger.Log(String.Format("Entering TVDBProvider.GetMedia(MediaClass,{0}", mergeType.ToString()));
            if (inputMedia.TvdbID > 0)
            {
                MediaClass mc = GetMediaByID(inputMedia.TvdbID);
                MediaClass retVal = Utilities.MediaUtil.MergeMediaObjects(config, inputMedia, mc, mergeType);
                logger.Log(String.Format("Exiting TVDBProvider.GetMedia(inputMedia,{0})", mergeType.ToString()));
                return (retVal);
            }
            if (!String.IsNullOrWhiteSpace(inputMedia.IMDBID))
            {
                TvdbSearchResult result = tvdbHandler.GetSeriesByRemoteId(ExternalId.ImdbId, inputMedia.IMDBID);
                if (result != null)
                {
                    MediaClass mc = GetMediaByID(result.Id);
                    MediaClass retVal = Utilities.MediaUtil.MergeMediaObjects(config, inputMedia, mc, mergeType);
                    logger.Log(String.Format("Exiting TVDBProvider.GetMedia(inputMedia,{0})", mergeType.ToString()));
                    return (retVal);
                }
            }
            logger.Log("Could not find the inputMedia via TMDB ID or IMDB ID");
            logger.Log(String.Format("Exiting TVDBProvider.GetMedia(inputMedia,{0})", mergeType.ToString()));
            return (inputMedia);
        }

        /// <summary>
        /// Gets the media from TVDB by ID.
        /// </summary>
        /// <param name="ID">TVDBID of the Media Object, has to be an int</param>
        /// <returns>MediaClass containing the TVDB Info</returns>
        public override MediaClass GetMediaByID(object ID)
        {
            logger.Log("Entering TVDBProvider.GetMediaByID(" + ID + ")");
            if (ID == null) throw new ArgumentNullException("ID");
            if (!(ID is int))
            {
                throw new ArgumentException("ID must be int for TVDBProvider::GetMediaByID");
            }
            var returnValue = new MediaClass(config);
            var imageUpdateManager = new ImageUpdateManager(config);
            TvdbSeries series = tvdbHandler.GetFullSeries((int)ID, language, true);
            if (series.AirsDayOfWeek != null)
            {
                returnValue.SeriesAirsDaysOfWeek.Add(series.AirsDayOfWeek);
            }
            if (!String.IsNullOrWhiteSpace(series.AirsTime))
            {
                try
                {
                    DateTime parsedTime = DateTime.Parse(series.AirsTime);
                    returnValue.SeriesAirsTime = parsedTime;
                }
                catch (Exception e)
                {
                    logger.Log(String.Format("Exception parsing series.AirsTime, msg:{0}", e.Message));
                    returnValue.SeriesAirsTime = null;
                }
            }
            else
            {
                returnValue.SeriesAirsTime = null;
            }

            if (base.downloadImages)
            {
                int count = 0;
                if (series.PosterPath != null)
                {
                    var poster = new ImageEntity();
                    poster.ImageSize = EImageSize.poster;
                    poster.ImageType = EImageType.backdrop;
                    returnValue.Backdrop = poster;
                    poster.URL = String.Format("{0}/{1}", baseImageURL, series.PosterPath);
                    imageUpdateManager.GetUpdate(poster);
                    count++;
                }

                foreach (TvdbPosterBanner poster in series.PosterBanners)
                {
                    var posterObj = new ImageEntity();
                    posterObj.ImageSize = EImageSize.poster;
                    posterObj.ImageType = EImageType.poster;
                    if (count == 1)
                    {
                        returnValue.Poster = posterObj;
                    }
                    else
                    {
                        returnValue.Images.Add(posterObj);
                    }
                    posterObj.URL = String.Format("{0}/{1}", baseImageURL, poster.BannerPath);
                    imageUpdateManager.GetUpdate(posterObj);
                    count++;
                    if (count > config.MaxImageCount)
                    {
                        break;
                    }
                }

                count = 0;
                if (series.BannerPath != null)
                {
                    var ie = new ImageEntity { ImageSize = EImageSize.original, ImageType = EImageType.banner };
                    returnValue.Images.Add(ie);
                    ie.URL = String.Format("{0}/{1}", baseImageURL, series.BannerPath);
                    imageUpdateManager.GetUpdate(ie);
                    count++;
                }

                foreach (TvdbBanner banner in series.Banners)
                {
                    var ie = new ImageEntity { ImageSize = EImageSize.original, ImageType = EImageType.banner };
                    returnValue.Images.Add(ie);
                    returnValue.Images.Add(ie);
                    ie.URL = String.Format("{0}/{1}", baseImageURL, banner.BannerPath);
                    imageUpdateManager.GetUpdate(ie);
                    count++;
                    if (count > config.MaxImageCount)
                    {
                        break;
                    }
                }

                count = 0;
                if (series.FanartPath != null)
                {
                    var ie = new ImageEntity { ImageSize = EImageSize.original, ImageType = EImageType.banner };
                    returnValue.Images.Add(ie);
                    ie.URL = String.Format("{0}/{1}", baseImageURL, series.FanartPath);
                    imageUpdateManager.GetUpdate(ie);
                    count++;
                }
                foreach (TvdbFanartBanner banner in series.FanartBanners)
                {
                    var ie = new ImageEntity { ImageSize = EImageSize.original, ImageType = EImageType.banner };
                    returnValue.Images.Add(ie);
                    ie.URL = String.Format("{0}/{1}", baseImageURL, banner.BannerPath);
                    imageUpdateManager.GetUpdate(ie);
                    count++;
                    if (count > config.MaxImageCount)
                    {
                        break;
                    }
                }
            }

            // Now deal with Episodes
            foreach (TvdbEpisode episode in series.Episodes)
            {
                var ee = new EpisodeEntity
                             {
                                 AbsoluteNumber = episode.AbsoluteNumber,
                                 AirsAfterSeason = episode.AirsAfterSeason,
                                 AirsBeforeSeason = episode.AirsBeforeSeason
                             };
                if (base.downloadImages)
                {
                    var banner = new ImageEntity { ImageSize = EImageSize.original, ImageType = EImageType.banner };
                    ee.Banner = banner;
                    banner.URL = String.Format("{0}/{1}", baseImageURL, episode.BannerPath);
                    imageUpdateManager.GetUpdate(banner);
                }
                foreach (string director in episode.Directors)
                {
                    var pe = new PersonEntity { Name = director };
                    pe.Job.Add("Director");
                    ee.Cast.Add(pe);
                }
                ee.DvdChapter = episode.DvdChapter;
                ee.DvdDiscID = episode.DvdDiscId;
                ee.DvdEpisodeNumber = episode.DvdEpisodeNumber;
                ee.DvdSeason = episode.DvdSeason;
                ee.EpisodeName = episode.EpisodeName;
                ee.EpisodeNumber = episode.EpisodeNumber;
                ee.FirstAired = episode.FirstAired;
                ee.IMDBID = episode.ImdbId;
                ee.IsSpecial = episode.IsSpecial;
                ee.Language = episode.Language.Name;
                ee.Overview = episode.Overview;
                ee.ProductionCode = episode.ProductionCode;
                ee.Rating = episode.Rating;
                foreach (var guest in episode.GuestStars)
                {
                    var pe = new PersonEntity { Name = guest };
                    pe.Job.Add("Guest Star");
                    ee.Cast.Add(pe);
                }
                ee.SeasonID = episode.SeasonId;
                ee.SeasonNumber = episode.SeasonNumber;
                ee.SeriesID = episode.SeriesId;
                ee.TvdbID = episode.SeriesId;
                returnValue.Episodes.Add(ee);
            }

            foreach (TvdbActor actor in series.TvdbActors)
            {
                PersonEntity pe = new PersonEntity();
                pe.Name = actor.Name;
                pe.TVDBID = actor.Id;

                if (base.downloadImages)
                {
                    ImageEntity ie = new ImageEntity();
                    ie.ImageSize = EImageSize.original;
                    ie.ImageType = EImageType.profile;
                    pe.Image = ie;
                    ie.URL = String.Format("{0}/{1}", baseImageURL, actor.ActorImage.BannerPath);
                    imageUpdateManager.GetUpdate(ie);
                }
                FilmographyEntity fe = new FilmographyEntity();
                fe.TVDBID = series.Id;
                fe.MovieTitle = series.SeriesName;
                fe.Job = "Actor";
                fe.IMDBID = series.ImdbId;
                fe.Character = actor.Role;
                fe.MoviePoster = returnValue.Poster;
                pe.Filmography.Add(fe);
                returnValue.Cast.Add(pe);
            }

            foreach (string genre in series.Genre)
            {
                returnValue.Genre.Add(genre);
            }

            returnValue.Languages.Add(series.Language.Name);
            returnValue.NetworkAffiliation = series.Network;
            returnValue.Overview = series.Overview;
            returnValue.Rating = series.Rating;
            returnValue.RunTime = new TimeSpan(0, (int)series.Runtime, 0);
            returnValue.Name = series.SeriesName;
            imageUpdateManager.WaitForUpdates();
            returnValue.IMDBID = series.ImdbId;

            logger.Log("Exiting TVDBProvider.GetMediaByID(" + ID + ")");

            return returnValue;
        }

        public override MediaClass GetUpdateForMedia(MediaClass inputMedia, MediaMergeType MergeType)
        {
            throw new NotImplementedException();
        }

        public override VersionInfo GetVersionInfo()
        {
            VersionInfo verInfo;
            verInfo.Name = Assembly.GetExecutingAssembly().GetName().Name;
            verInfo.MajorVersion = Assembly.GetExecutingAssembly().GetName().Version.Major;
            verInfo.MinorVersion = Assembly.GetExecutingAssembly().GetName().Version.Minor;
            verInfo.BuildNumber = Assembly.GetExecutingAssembly().GetName().Version.Revision;
            return verInfo;
        }

        public override bool Run()
        {
            throw new NotImplementedException();
        }

        public override List<MediaSearchReturn> SearchForMedia(MediaClass mediaObject)
        {
            logger.Log("Entering TVDBProvider.SearchForMedia(MediaClass)");
            if (mediaObject == null)
            {
                logger.Log(Logger.Levels.WARN, "mediaObject==null/empty, returning null");
                logger.Log("Exiting TVDBProvider.SearchForMediaByName(mediaObject), rc==null");
                return (null);
            }

            var mediaList = new List<MediaSearchReturn>();

            // First check to see if one of the IDs we support is set, which for this provider is TMDBID and IMDBID
            if (!String.IsNullOrWhiteSpace(mediaObject.IMDBID))
            {
                logger.Log("Searching based on IMDBID");
                var searchResult = tvdbHandler.GetSeriesByRemoteId(ExternalId.ImdbId, mediaObject.IMDBID);
                if (searchResult != null)
                {
                    var retVal = new MediaSearchReturn
                                     {
                                         IMDBID = searchResult.ImdbId,
                                         TVDBID = searchResult.Id,
                                         name = searchResult.SeriesName
                                     };
                    mediaList.Add(retVal);
                    logger.Log(String.Format("Found movie via IMDB ID: {0}", retVal.name));
                }
            }

            // Next TVDBID
            if (mediaObject.TvdbID > 0)
            {
                logger.Log("Searching based on TVDBID");
                var searchResult = tvdbHandler.GetSeries(mediaObject.TvdbID, language, false, false, false);
                if (searchResult != null)
                {
                    MediaSearchReturn retVal = new MediaSearchReturn
                                                   {
                                                       IMDBID = searchResult.ImdbId,
                                                       TVDBID = searchResult.Id,
                                                       name = searchResult.SeriesName
                                                   };
                    mediaList.Add(retVal);
                    logger.Log(String.Format("Found movie via TVDB ID: {0}", retVal.name));
                }
            }

            if (!String.IsNullOrWhiteSpace(mediaObject.Title))
            {
                var nameSearch = mediaObject.Released != null ? SearchForMediaByNameAndYear(mediaObject.Title, mediaObject.Released.Value.Year) : SearchForMediaByName(mediaObject.Title);
                if (nameSearch != null)
                {
                    mediaList.AddRange(nameSearch);
                    nameSearch.Clear();
                }
            }

            // Our scoring is:
            //  100 = Same IMDB, TMDB or TVDB ID (And isnt null)
            //  Standard name/year scoring
            var returnValue = new List<MediaSearchReturn>();
            foreach (var msr in mediaList)
            {
                if (!String.IsNullOrWhiteSpace(msr.IMDBID) && msr.IMDBID.Equals(mediaObject.IMDBID))
                {
                    msr.pctLikelyMatch = 100;
                }
                if (msr.TMDBID != 0 && msr.TMDBID == mediaObject.TmdbID)
                {
                    msr.pctLikelyMatch = 100;
                }
                if (msr.TVDBID != 0 && msr.TVDBID == mediaObject.TvdbID)
                {
                    msr.pctLikelyMatch = 100;
                }
                returnValue.Add(msr);
            }

            // Now remove duplicates
            var tmp = new List<MediaSearchReturn>();
            foreach (var msr in returnValue)
            {
                var dupe = false;
                foreach (var tmsr in tmp)
                {
                    if (tmsr.TMDBID == msr.TMDBID && tmsr.TMDBID != 0)
                    {
                        dupe = true;
                        break;
                    }
                    if (tmsr.IMDBID != null)
                    {
                        if (tmsr.IMDBID.Equals(msr.IMDBID))
                        {
                            dupe = true;
                            break;
                        }
                    }
                    if (tmsr.TVDBID == msr.TVDBID && tmsr.TVDBID != 0)
                    {
                        dupe = true;
                        break;
                    }
                }
                if (!dupe)
                {
                    tmp.Add(msr);
                }
            }
            tmp.Sort();
            tmp.Reverse();
            logger.Log("Exiting TVDBProvider.SearchForMediaByName(mediaObject), rc==" + tmp.Count);
            return tmp;
        }

        public override List<MediaSearchReturn> SearchForMedia(MediaClass mediaObject, int maxReturns)
        {
            logger.Log("Entering TVDBProvider.SearchForMediaByName(mediaObject, " + maxReturns + ")");
            var returnValue = SearchForMedia(mediaObject);
            while (returnValue.Count > maxReturns)
            {
                returnValue.RemoveAt(returnValue.Count);
            }
            logger.Log("Exiting TVDBProvider.SearchForMediaByName(mediaObject, " + maxReturns + "), rc==" +
                       returnValue.Count + " return values");
            return returnValue;
        }

        public override List<MediaSearchReturn> SearchForMediaByName(string name)
        {
            logger.Log("Entering TVDBProvider.SearchForMediaByName(" + name + ")");
            List<MediaSearchReturn> returnValue = new List<MediaSearchReturn>();
            List<TvdbSearchResult> results = tvdbHandler.SearchSeries(name, language);

            foreach (TvdbSearchResult result in results)
            {
                MediaSearchReturn msr = new MediaSearchReturn();
                msr.IMDBID = result.ImdbId;
                msr.TVDBID = result.Id;
                msr.name = result.SeriesName;

                msr.pctLikelyMatch = 75 - (Strings.ComputeStringDistance(msr.name, name) * 2);
                if (msr.name.ToUpper().Contains(name.ToUpper()))
                {
                    msr.pctLikelyMatch += 10;
                }
                if (msr.pctLikelyMatch < 0)
                {
                    msr.pctLikelyMatch = 0;
                }
                if (msr.pctLikelyMatch > 100)
                {
                    msr.pctLikelyMatch = 100;
                }
                returnValue.Add(msr);
                logger.Log(String.Format("TVDB Series found: {0} {1}% likely match", msr.name, msr.pctLikelyMatch));
            }
            logger.Log(String.Format("Exiting TVDBProvider.SearchForMediaByName({0}) {1} matches", name, returnValue.Count));
            return (returnValue);
        }

        public override List<MediaSearchReturn> SearchForMediaByName(string name, int maxReturns)
        {
            logger.Log("Entering TVDBProvider.SearchForMediaByName(" + name + "," + maxReturns + ")");
            List<MediaSearchReturn> returnValue = SearchForMediaByName(name);
            if (returnValue == null)
            {
                logger.Log("Exiting TMDBProvider.SearchForMediaByName(" + name + "," + maxReturns + ") 0 matches");
                return null;
            }
            returnValue.Sort();
            returnValue.Reverse();

            if (returnValue.Count < maxReturns)
            {
                logger.Log("Exiting TVDBProvider.SearchForMediaByName(" + name + "," + maxReturns + ") " +
                           returnValue.Count + " matches");
                return returnValue;
            }

            returnValue.RemoveRange(maxReturns, returnValue.Count - maxReturns);
            logger.Log("Exiting TVDBProvider.SearchForMediaByName(" + name + "," + maxReturns + ") " + returnValue.Count +
                       " matches");
            return returnValue;
        }

        public override List<MediaSearchReturn> SearchForMediaByNameAndYear(string name, int year)
        {
            logger.Log("Entering SearchForMediaByNameAndYear(" + name + "," + year + ")");
            List<MediaSearchReturn> tmp = SearchForMediaByName(name);

            // If the year is the same as the year we are searching for, we add 10 to the score
            if (tmp == null)
            {
                logger.Log("Entering SearchForMediaByNameAndYear(" + name + "," + year + ") 0 matches");
                return null;
            }
            List<MediaSearchReturn> returnValue = new List<MediaSearchReturn>();
            foreach (MediaSearchReturn msr in tmp)
            {
                // Get the full series so we can see if the year matches for any episode
                TvdbSeries series = tvdbHandler.GetFullSeries(msr.TVDBID, language, false);
                bool yearMatch = false;
                foreach (TvdbEpisode episode in series.Episodes)
                {
                    if (episode.FirstAired.Year == year)
                    {
                        yearMatch = true;
                        break;
                    }
                }
                if (yearMatch)
                {
                    msr.pctLikelyMatch += 10;
                }
                returnValue.Add(msr);
            }
            logger.Log("Entering SearchForMediaByNameAndYear(" + name + "," + year + ") " + returnValue.Count +
                       " matches");
            returnValue.Sort();
            returnValue.Reverse();

            return returnValue;
        }

        public override List<MediaSearchReturn> SearchForMediaByNameAndYear(string name, int year, int maxReturns)
        {
            logger.Log("Entering SearchForMediaByNameAndYear(" + name + "," + year + "," + maxReturns + ")");
            List<MediaSearchReturn> returnValue = SearchForMediaByNameAndYear(name, year);
            returnValue.Sort();
            returnValue.Reverse();
            if (returnValue.Count < maxReturns)
            {
                logger.Log("Entering SearchForMediaByNameAndYear(" + name + "," + year + "," + maxReturns + ") " +
                           returnValue.Count + " matches");
                return returnValue;
            }
            returnValue.RemoveRange(maxReturns, returnValue.Count - maxReturns);
            logger.Log("Entering SearchForMediaByNameAndYear(" + name + "," + year + "," + maxReturns + ") " +
                       returnValue.Count + " matches");

            return returnValue;
        }

        public override void SetDefaultConfig()
        {
            // Config Variables are:
            // Name - Language
            // Type - String
            // Provider ID - This guys ID
            // Description - The language you want to download movie info in (Default English)
            // Value - English

            logger.Log("Entering TVDBProvider.SetDefaultConfig()");
            VersionInfo vi = GetVersionInfo();
            base.pluginEntity.BuildNumber = vi.BuildNumber;
            base.pluginEntity.MajorVersion = vi.MajorVersion;
            base.pluginEntity.MinorVersion = vi.MinorVersion;
            base.pluginEntity.Name = vi.Name;
            base.pluginEntity.SaveOrUpdate();

            var ciH = new ConfigItemsHelper(config);

            ciH.CreateCIEntry(base.pluginEntity.ID, "Language", EValueType.STRING, "en",
                              "Language movie information will be downloaded in");
            logger.Log(
                String.Format("Set TVDBProvider Variable - Name: Language, type: string, value: en, ProviderID: {0}",
                              base.pluginEntity.ID));

            var Extensions = new string[17, 2]
                                 {
                                     {
                                         "AVI",
                                         "Common video container format.  AVI is the abbreviation for Audio Video Interleve format developed by Microsoft"
                                     },
                                     {"263", "H.263 encoded video file"},
                                     {"264", "H.264/MPEG-4 AVC video file"},
                                     {"bdmv", "Blu-ray information file"},
                                     {"divx", "DivX Media Format"},
                                     {"dvr-ms", "Microsoft Digital Video Recording"},
                                     {"m2t", "MPEG movie file"},
                                     {"m2ts", "MPEG-2 stream (Blu-Ray)"},
                                     {"m4v", "MPEG-4 video file format"},
                                     {"mkv", "Matroska video-audio multimedia file"},
                                     {"mov", "Apple QuickTime digital movie file"},
                                     {"mp4", "MPEG-4 video file format"},
                                     {"mpeg", "MPEG Movie"},
                                     {"mpg", "ProgDVB MPEG2 video file"},
                                     {"wmv", "Windows Media Video"},
                                     {"xvid", "XviD Codec"},
                                     {"wtv", "Windows Media Center recorded television file"}
                                 };
            if (base.pluginEntity.ExtensionsHandled == null)
            {
                base.pluginEntity.ExtensionsHandled = new List<MediaFileTypesEntity>();
            }

            for (int i = 0; i < Extensions.Length / 2; i++)
            {
                var tmp = new MediaFileTypesEntity();
                tmp.Description = Extensions[i, 1];
                tmp.Extension = Extensions[i, 0];
                tmp.SaveOrUpdate();
                base.pluginEntity.ExtensionsHandled.Add(tmp);
            }

            base.pluginEntity.SaveOrUpdate();
            logger.Log("Exiting TVDBProvider.SetDefaultConfig()");
        }

        #endregion Methods
    }
}